# coding:utf-8
from flask import request, Blueprint, render_template, redirect, url_for, jsonify
from flask_login import current_user

from .register_fm import RegisterFM
from .roles_fm import RolesFM
from ..models.role_md import RoleMD

admin_bp = Blueprint('admin', __name__, url_prefix='/admin/', static_folder=None)
from ..services.user_admin_svr import UserAdminSVR


# login 页面
@admin_bp.route("author/login", methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        if current_user.is_authenticated:
            return redirect("/")
        else:
            return render_template("/core/admin/login.html")


# register 页面
@admin_bp.route("register", methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        register_fm = RegisterFM()
        return render_template("/core/admin/register.html", form=register_fm)


@admin_bp.route('register/submit', methods=('GET', 'POST'))
def register_submit():
    register_fm = RegisterFM()
    if register_fm.validate_on_submit():
        register_fm = RegisterFM()
        ua_svr = UserAdminSVR()
        ua_svr.register(register_fm.name.data, register_fm.pwd.data)
        return url_for("login")
    return render_template("/core/admin/login.html", form=register_fm)


# 角色管理页面
@admin_bp.route("roles", methods=('GET', 'POST'))
def roles():
    if request.method == 'GET':
        roles = UserAdminSVR.get_all_roles()
        roles_fm = RolesFM()
        return render_template("/core/admin/roles.html", roles=roles, form=roles_fm)


@admin_bp.route("update_role", methods=('GET', 'POST'))
def update_role():
    """
    更新角色信息视图函数
    Returns:

    """
    role_id = request.values.get("role_id", type=str, default=None)
    roles_fm = RolesFM()
    if request.method == 'GET':
        # 如果role_id存在，则填充表单
        if role_id is not None:
            role_md = RoleMD.get(role_id)
            roles_fm.update_self(role_md)
        return render_template("/core/admin/role_fm.html", form=roles_fm)
    if request.method == 'POST':
        try:
            if roles_fm.validate_on_submit():
                role_name = roles_fm.role_name.data
                role_type = roles_fm.role_type.data
                if roles_fm.parent_role.data is not None:
                    role_parent_id = roles_fm.parent_role.data.id
                else:
                    role_parent_id = None
                if role_id == "":
                    UserAdminSVR.create_role(role_name, role_type, role_parent_id)
                    return jsonify({'success': True, 'msg': "添加角色成功！"}), 200, {'ContentType': 'application/json'}
                else:
                    UserAdminSVR.update_role(role_id, role_name, role_type, role_parent_id)
                    return jsonify({'success': True, 'msg': "修改角色成功！"}), 200, {'ContentType': 'application/json'}
            else:
                return render_template("/core/admin/role_fm.html", form=roles_fm)
        except Exception as e:
            return jsonify({'success': False, 'msg': "操作失败！"}), 200, {'ContentType': 'application/json'}


@admin_bp.route("del_role", methods=('GET',))
def del_role():
    role_id = request.values.get("role_id", type=str, default=None)
    force_del = request.values.get("force_del", type=int, default=0)
    status, msg = UserAdminSVR.delete_role(role_id, force_del)
    return jsonify({'success': status, 'msg': msg}), 200, {'ContentType': 'application/json'}


@admin_bp.route("", methods=['GET', 'POST'])
def index():
    return render_template("/index.html")
